<?php

class EmployeesController extends AppController
{

    var $name = 'Employees';

    function beforeFilter()
    {
        parent::beforeFilter();
    }

    function login()
    {
        if( !empty($this->data) && $this->Auth->user() )
        {
            //pr($this->data);
            $this->Employee->id = $this->Auth->User('id');
            $this->Employee->saveField('lastlogin', date('Y-m-d H:i:s'));
            $this->redirect(APP_URL);
        }
    }

    function logout()
    {
        $this->redirect($this->Auth->logout());
    }

    function dashboard()
    {
        $assignedpotentials = $this->Employee->Potential->find('all', array(
            'conditions' => array(
                'Potential.assignedtoemployee_id' => $this->Session->read('Auth.Employee.id')
            ),
            'contain' => array(
                'User' => array(
                    'fields' => array('id','firstname','lastname')
                ),
                'Location' => array(
                    'fields' => array('')
                ),
                'Employee' => array(
                    'fields' => array('id', 'firstname', 'lastname')
                ),
                'Product' => array(
                    'fields' => array('id', 'name')
                )
            ),
            'order' => array('Potential.created' => 'desc'),
            'limit' => '0, 20'
        ));

        $assignedactivities = $this->Employee->Potentialactivity->find('all', array(
            'conditions' => array(
                'Potentialactivity.assignedtoemployee_id' => $this->Session->read('Auth.Employee.id')
            ),
            'contain' => array(
                'Potential' => array(
                    'User' => array(
                        'fields' => array('id','firstname','lastname','email1')
                    ),
                    'Product' => array(
                        'fields' => array('id','name')
                    )
                ),
                'Activitytype' => array(
                    'fields' => array('id','name')
                ),
                'Employee' => array(
                    'fields' => array('id','firstname','lastname','primaryemail')
                ),
                'Assignedtoemployee' => array(
                    'fields' => array('id','firstname','lastname','primaryemail')
                )
            ),
            'order' => array('Potentialactivity.created' => 'desc'),
            'limit' => '0, 20'
        ));

        $this->set(compact('assignedpotentials','assignedactivities'));
    }

    function index()
    {
        $this->Employee->recursive = 0;
        $this->set('employees', $this->paginate());
    }

    function view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid employee', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('employee', $this->Employee->read(null, $id));
    }

    function admin_login()
    {
        if( !empty($this->data) && $this->Auth->user() )
        {
            //pr($this->data);
            $this->Employee->id = $this->Auth->User('id');
            $this->Employee->saveField('lastlogin', date('Y-m-d H:i:s'));
            $this->redirect(array('controller' => 'employees', 'action' => 'home', 'admin' => true));
        }
    }

    function admin_logout()
    {
        $this->redirect($this->Auth->logout());
    }

    function admin_home()
    {

    }

    function admin_index()
    {
        if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
        {
            //pr($this->params);
            $this->autoRender = false;

            // get how many rows we want to have into the grid - rowNum parameter in the grid
            $limit = $this->params['url']['rows'];

            // get index row - i.e. user click to sort. At first time sortname parameter -
            // after that the index from colModel
            $sidx = $this->params['url']['sidx'];

            // sorting order - at first time sortorder
            $sord = $this->params['url']['sord'];

            $page = $this->params['url']['page'];

            // if we not pass at first time index use the first column for the index or what you want
            if( !$sidx ) $sidx = 1;

            // calculate the number of rows for the query. We need this for paging the result
            $row = $this->Employee->find('count');
            $count = $row;

            // calculate the total pages for the query
            if( $count > 0 )
            {
                $total_pages = ceil($count / $limit);
            }
            else
            {
                $total_pages = 0;
            }

            // if for some reasons the requested page is greater than the total
            // set the requested page to total page
            if( $page > $total_pages ) $page = $total_pages;

            // calculate the starting position of the rows
            $start = $limit * $page - $limit;

            // if for some reasons start position is negative set it to 0
            // typical case is that the user type 0 for the requested page
            if( $start < 0 ) $start = 0;

            // the actual query for the grid data
            $limit_range = $start . "," . $limit;
            $sort_range = 'Employee.' . $sidx . " " . $sord;

            $this->Employee->recursive = -1;

            if( $this->params['url']['_search'] == 'true' )
            {
                if( isset($this->params['url']['firstname']) && !empty($this->params['url']['firstname']) )
                {
                    $searchcondition = array('Employee.firstname LIKE' => '%' . $this->params['url']['firstname'] . '%');
                }
                else
                {
                    $searchcondition = array('Employee.lastname LIKE' => '%' . $this->params['url']['lastname'] . '%');
                }

                $result = $this->Employee->find('all', array(
                    'fields' => array('id', 'firstname', 'lastname'),
                    'conditions' => $searchcondition,
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }
            else
            {
                $result = $this->Employee->find('all', array(
                    'fields' => array('id', 'firstname', 'lastname'),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }

            $i = 0;
            $response->page = $page;
            $response->total = $total_pages;
            $response->records = $count;

            foreach($result as $result)
            {
                $response->rows[$i]['id'] = $result['Employee']['id'];

                $firstname = "<a href='" . APP_URL . "admin/employees/view/" . $result['Employee']['id'] . "'>" . $result['Employee']['firstname'] . "</a>";
                $lastname = "<a href='" . APP_URL . "admin/employees/view/" . $result['Employee']['id'] . "'>" . $result['Employee']['lastname'] . "</a>";
                $view = "<a title='view' href='" . APP_URL . "admin/employees/view/" . $result['Employee']['id'] . "'>view</a>";
                $edit = "<a title='edit' href='" . APP_URL . "admin/employees/edit/" . $result['Employee']['id'] . "'>edit</a>";
                $delete = "<a title='delete' href=\"#\" onclick=\"if(confirm('Are you sure you want to delete this ?')){window.location.href= '" . APP_URL . "admin/employees/delete/" . $result['Employee']['id'] . "'}\">delete</a>";
                $actions = $view . "    " . $edit . "    " . $delete;

                $response->rows[$i]['cell'] = array($firstname, $lastname, $actions);
                $i++;
            }

            echo json_encode($response);
            //exit;
        }
    }

    function admin_view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid employee', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('employee', $this->Employee->read(null, $id));
    }

    function admin_add()
    {
        $this->_addEmployee();
    }

    function admin_edit($id = null)
    {
        $this->_editEmployee($id);
    }

    function admin_delete($id = null)
    {
        $this->_deleteEmployee($id);
    }

    /**
     * ajax action, will check if an email entered by user is already used up in the database
     */
    function checkEmail()
    {
        if( $this->RequestHandler->isAjax() && preg_match("/([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})/", $this->params['url']['email']) )
        {
            $emailExists = $this->Employee->field('id', array('primaryemail' => $this->params['url']['email']));
            if( $emailExists )
            {
                echo "1";
            }
            else
            {
                echo "0";
            }
            exit();
        }
    }

    function _addEmployee()
    {
        if( !empty($this->data) )
        {
            $this->Employee->create();
            if( $this->Employee->save($this->data) )
            {
                $this->Session->setFlash(__('The employee has been added successfully', true), 'success');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The employee could not be added. Please, try again.', true), 'notice');
            }
        }

        $states = $this->Employee->City->State->find('list');

        $employeetypes = $this->Employee->Employeetype->find('list', array(
            'conditions' => array('Employeetype.id !=' => Configure::read('employeetype.admin.id'))
        ));

        $departments = $this->Employee->Department->find('list');

        $locations = $this->Employee->Location->find('list');

        $this->set(compact('states', 'employeetypes', 'departments', 'locations'));
    }

    function _editEmployee($id = null)
    {
        if( !$id && empty($this->data) )
        {
            $this->Session->setFlash(__('Invalid employee', true), 'error');
            $this->redirect(array('action' => 'index'));
        }
        if( !empty($this->data) )
        {
            if( $this->Employee->save($this->data) )
            {
                $this->Session->setFlash(__('The employee has been edited successfully', true), 'notice');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The employee could not be edited. Please, try again.', true), 'notice');
            }
        }
        if( empty($this->data) )
        {
            $this->data = $this->Employee->find('first', array(
                'conditions' => array('Employee.id' => $id),
                'contain' => array(
                    'City' => array(
                        'fields' => array('id', 'name'),
                        'State' => array(
                            'fields' => array('id', 'name')
                        )
                    )
                )
            ));
        }

        $states = $this->Employee->City->State->find('list');
        $employeetypes = $this->Employee->Employeetype->find('list');
        $departments = $this->Employee->Department->find('list');
        $locations = $this->Employee->Location->find('list');
        $this->set(compact('states', 'employeetypes', 'departments', 'locations'));
    }

    function _deleteEmployee($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid id for employee', true));
            $this->redirect(array('action' => 'index'));
        }
        if( $this->Employee->delete($id) )
        {
            $this->Session->setFlash(__('Employee deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Employee was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

}

?>